package com.baiyangtx.lingerweather;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;

import com.baiyangtx.lingerweather.adapt.CityKey;
import com.baiyangtx.lingerweather.model.DefaultWeatherChartModel;
import com.baiyangtx.lingerweather.model.MapChartModel;
import com.baiyangtx.lingerweather.observer.WeatherObserver;
import com.baiyangtx.lingerweather.service.DataService;
import com.baiyangtx.lingerweather.view.WC;

@SuppressLint("DefaultLocale")
public class MainActivity extends Activity {

	private static final int REQUEST_CODE_CITYMANAGER = 1 ;
	
	
	
	
	private TextView city ;
	private TextView temperature ;
	private TextView recentWeather ;
	private TextView feeling ;
	private TextView feeling_desc ;
	private TextView wind ;
	private TextView wind_power ;
	private TextView syncTime ;
	
	private ImageButton btnAddCity ;
	private ImageButton btnSyncCity ;
	private ImageButton btnSettings ;
	
	
	private WC chart ;
	
	private DataService mService ;
	
	private final WeatherObserver mWeatherObserver = new WeatherObserver() {
		
		@Override
		public void onWeatherUpdata(Map<String, String> city) {
			if( city.get(CityKey.SYNC_TIME) != null ){
				setCity(city) ;
			}else{
				setDefault() ;
			}
		}
		
		@Override
		public void onSubjectCityChange(String cityName) {
			Map<String, String> map = mService.getSubjectCity() ;
			if( map.get(CityKey.SYNC_TIME) != null ){
				setCity(map) ;
			}else{
				setDefault() ;
			}
			city.setText(map.get(cityName) ) ; 
		}
	};
	
	
	
	
	private final ServiceConnection mConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			
		}
		
		
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder binder) {
			
			DataService.MBinder mbinder = (DataService.MBinder)binder ;
			mService = mbinder.getService() ;
			mService.attachWeatherObserver(mWeatherObserver) ;
			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					setContentView(R.layout.active_main) ;
					findViews();
					bindOnClickListener() ;
					setSubjectCity() ;
				}
			}, 3000) ;
		}
	};
	
	
	
	private final View.OnClickListener onClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if( v.equals(btnAddCity) ){
				Intent intent = new Intent( MainActivity.this , CityMangerActivity.class) ;
				startActivityForResult(intent, REQUEST_CODE_CITYMANAGER ) ;
			}else if( v.equals(btnSettings)){
				Intent intent = new Intent( MainActivity.this , SettingActivity.class) ;
				startActivity(intent) ;
			}else if( v.equals(btnSyncCity) ){
				syncTime.setText("同步中");
				postSyncTask() ;
			}
		}
	};
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.requestWindowFeature( Window.FEATURE_NO_TITLE ) ;
		Intent intent = new Intent(this , DataService.class ) ;
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE );
		setContentView(R.layout.lancher);
	}
	
	@Override
	protected void onDestroy() {
		unbindService(mConnection) ;
		super.onDestroy();
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CITYMANAGER ) {
			String code = data.getStringExtra( CityKey.CITY_CODE );
			String name = data.getStringExtra( CityKey.CITY_NAME ) ;
			mService.setSubjectCity(code, name) ;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.activity_main, menu);
//		return true;
//	}
//	
	
	
	private void findViews(){
		city = (TextView)findViewById(R.id.txt_city) ;
		temperature = (TextView)findViewById(R.id.txt_temperature) ;
		recentWeather = (TextView)findViewById(R.id.txt_weather) ;
		feeling  = (TextView)findViewById(R.id.txt_feeling) ;
		feeling_desc  = (TextView)findViewById(R.id.txt_feelingDescription) ;
		wind  = (TextView)findViewById(R.id.txt_wind ) ;
		wind_power = (TextView)findViewById(R.id.txt_windPower) ;
		syncTime  = (TextView)findViewById(R.id.txt_updateTime ) ;
		
		btnAddCity  = (ImageButton)findViewById(R.id.btn_addCity) ;
		btnSettings = (ImageButton)findViewById(R.id.btn_set ) ;
		btnSyncCity = (ImageButton)findViewById(R.id.btn_syncData ) ;
		
		chart = (WC)findViewById(R.id.chart) ;
		
	}
	
	
	private void bindOnClickListener(){
		btnAddCity.setOnClickListener(onClickListener) ;
		btnSettings.setOnClickListener(onClickListener) ;
		btnSyncCity.setOnClickListener(onClickListener) ;
	}
	
	
	
	
	
	/*
	 * make sure map is not null.
	 */
	@SuppressLint( "DefaultLocale" )
	private void setCity(Map<String , String >  c ){
		city.setText( c.get(CityKey.CITY_NAME) ) ;
		
		temperature.setText( c.get(CityKey.REAL_TEMPERATURE )+"℃") ;
		recentWeather.setText( CityKey.weatherToChinese(c.get(CityKey.RECENT_WEATHER)) ) ; ;
		feeling.setText( c.get(CityKey.FEELING)) ;
		feeling_desc.setText(c.get(CityKey.FEELING_DESCRIPTION)) ;
		wind.setText(c.get(CityKey.WIND)) ;
		wind_power.setText( c.get(CityKey.WIND_POWER)) ;
		

		setSyncTime( c.get(CityKey.SYNC_TIME)) ;
		
		if( c.get(CityKey.FUTURE_TEMP_HIGHT ) == null ){
			chart.setWeatherChartModel(new DefaultWeatherChartModel(this)) ;
		}else{
			try {
				MapChartModel model = new MapChartModel( this , c ) ;
				chart.setWeatherChartModel(model) ;
				chart.updataSuface() ; 
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	
	@SuppressLint("SimpleDateFormat")
	private void setSyncTime(String syncT ){
		if(syncT == null ){
			syncTime.setText("未同步") ;
			return ;
		}
		SimpleDateFormat format = new SimpleDateFormat(CityKey.FORMAT) ;
		Date date = null ;
		try {
			date = format.parse( syncT );
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		Calendar now = Calendar.getInstance() ;
		Calendar sync = Calendar.getInstance() ;
		sync.setTime(date) ;
		String ss = null ;
		if( sync.get(Calendar.YEAR) != now.get(Calendar.YEAR)){
			ss = String.format("%d年前", now.get(Calendar.YEAR) - sync.get(Calendar.YEAR) );
		}else if( sync.get(Calendar.MONTH) != now.get(Calendar.MONTH) ){
			ss = String.format("%d月前", now.get(Calendar.MONTH) - sync.get(Calendar.MONTH) );
		}else if( sync.get(Calendar.DATE) != now.get(Calendar.DATE) ){
			ss = String.format("%d天前", now.get(Calendar.DATE) - sync.get(Calendar.DATE) );
		}else{
			ss = String.format("%2d:%2d", sync.get(Calendar.HOUR_OF_DAY) , sync.get(Calendar.MINUTE) );
		}
		syncTime.setText( ss + " 更新") ;
	}
	
	
	
	
	private void setDefault(){
		city.setText( R.string.city ) ;
		temperature.setText( R.string.temperature ) ;
		recentWeather.setText( R.string.weather ) ; ;
		feeling.setText( R.string.feeling ) ;
		feeling_desc.setText( R.string.feeling_description ) ;
		wind.setText( R.string.wind ) ;
		wind_power.setText( R.string.wind_power ) ;
		syncTime.setText( R.string.updata_time ) ;
		DefaultWeatherChartModel model = new DefaultWeatherChartModel(getApplicationContext()) ;
		chart.setWeatherChartModel(model) ;
		chart.invalidate() ;
		postSyncTask() ;
	}
	
	
	private void postSyncTask(){
		mService.syncSubjectCity() ;
	}
	
	
	private void setSubjectCity(){
		Map<String,String> map = mService.getSubjectCity() ;
		if( map != null ){
			city.setText(map.get(CityKey.CITY_NAME) ) ; 
			if( map.get(CityKey.SYNC_TIME) != null ){
				setCity(map) ;
			}else{
				setDefault() ;
			}
		}
	}
	
	
}





















